Page({
  data: {
    oldPassword: '',
    newPassword: '',
    oldPasswordError: '',
    newPasswordError: '',
    canSubmit: false
  },

  onOldPasswordInput(e) {
    const oldPassword = e.detail.value;
    this.setData({ oldPassword });
    this.validateForm();
  },

  onNewPasswordInput(e) {
    const newPassword = e.detail.value;
    this.setData({ newPassword });
    this.validateForm();
  },

  validateForm() {
    const { oldPassword, newPassword } = this.data;
    let oldPasswordError = '';
    let newPasswordError = '';

    if (!oldPassword) {
      oldPasswordError = '请输入旧密码';
    }

    if (!newPassword) {
      newPasswordError = '请输入新密码';
    } else if (newPassword === oldPassword) {
      newPasswordError = '新密码不能与旧密码相同';
    } else if (!/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,16}$/.test(newPassword)) {
      newPasswordError = '密码需6-16位，包含字母和数字';
    }

    this.setData({
      oldPasswordError,
      newPasswordError,
      canSubmit: !oldPasswordError && !newPasswordError
    });
  },

  onConfirm() {
    const { oldPassword, newPassword } = this.data;
    wx.request({
      url: 'https://api.example.com/updatePassword',
      method: 'POST',
      data: { oldPassword, newPassword },
      success: (res) => {
        if (res.data.code === 0) {
          wx.showToast({ title: '密码修改成功', icon: 'success' });
          wx.navigateBack({ delta: 1 });
        } else {
          wx.showToast({ title: res.data.msg, icon: 'none' });
        }
      },
      fail: () => {
        wx.showToast({ title: '网络请求失败', icon: 'none' });
      }
    });
  }
})